<template>
  <section id="openOrder-section">
    <el-row class="section-box flex">
      <!--左侧 收银模块 -->
      <el-col :span="16" class="Cashier">
        <el-container>
          <el-main class="Casher-main flex-v">
            <el-row class="header flex">
              <el-col :span="8">销售单 {{ OrderNum }}</el-col>
              <el-col :span="2">
                <el-divider direction="vertical"></el-divider>
              </el-col>
              <el-col :span="4">
                件数
                <br />
                <span>{{ shopsData.length }}</span>
              </el-col>
              <el-col :span="2">
                <el-divider direction="vertical"></el-divider>
              </el-col>
              <el-col :span="8">
                金额(￥)
                <br />
                <span>{{ saleActualSum }}</span>
              </el-col>
            </el-row>
            <el-row class="search">
              <el-col>
                <el-autocomplete
                  popper-class="my-autocomplete"
                  v-model="inputShopName"
                  :fetch-suggestions="query"
                  placeholder="请输入商品名称"
                  @select="selected"
                  suffix-icon="el-icon-search"
                >
                  <template slot-scope="{ item }">
                    <span class="name">{{ item.shopName }}</span>
                  </template>
                </el-autocomplete>
              </el-col>
            </el-row>
            <el-row class="goods-listBox">
              <el-col>
                <el-table
                  :data="shopsData"
                  height="100%"
                  style="width: 100%"
                  ref="singleTable"
                  highlight-current-row
                  @current-change="selectedRow"
                >
                  <el-table-column label="序号" width="60">
                    <template slot-scope="scope">
                      <div class="center">
                        <span>{{ shopsData.length - scope.$index }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="名称(￥)">
                    <template slot-scope="scope">
                      <span class="shopName">{{ scope.row.shopName }}</span>
                      <br />
                      <span class="shopCode" v-if="scope.row.shopCode">
                        {{
                        scope.row.shopCode
                        }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column width="100" label="售价">
                    <template slot-scope="scope">
                      <span class="font">{{ scope.row.salePrice }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column width="60" label="数量">
                    <template slot-scope="scope">
                      <span class="font">{{ scope.row.num }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="小计(￥)" width="100">
                    <template slot-scope="scope">
                      <div class="font">
                        <span class="acturalPrice">{{ scope.row.acturalPrice }}</span>
                        <br />
                        <span
                          v-if="scope.row.BeforePrice"
                          class="hadDiscount"
                        >{{ scope.row.BeforePrice }}</span>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-main>
          <el-aside style="width:140px">
            <el-row class="btn-box">
              <el-col>
                <el-button class="toPay" id="toPay" @click="mainFuns(1)">
                  结账&nbsp;
                  <strong>+</strong>
                </el-button>
                <el-button class="member" id="member" @click="mainFuns(2)">
                  会员&nbsp;
                  <strong>F6</strong>
                </el-button>
                <el-button id="modifyNum" @click="mainFuns(3)">
                  数量&nbsp;
                  <strong>*</strong>
                </el-button>
                <el-button id="delLine" @click="mainFuns(4)">
                  删行&nbsp;
                  <strong>Del</strong>
                </el-button>
                <el-button id="modifyPrice" @click="mainFuns(5)">
                  改售价&nbsp;
                  <strong>F4</strong>
                </el-button>
                <el-button id="modifyDiscount" @click="mainFuns(6)">
                  单品优惠&nbsp;
                  <strong>F8</strong>
                </el-button>
                <el-button id="more" @click="mainFuns(7)">
                  更多&nbsp;
                  <strong>F11</strong>
                </el-button>
              </el-col>
            </el-row>
          </el-aside>
        </el-container>
      </el-col>
      <!-- 右侧 收藏、推荐模块 -->
      <el-col :span="8" class="Collection">
        <el-container>
          <el-header style="height:auto;padding:0;">
            <el-row class="Record-member flex flex-vc">
              <el-col v-if="!surePayFlag">
                <span>按F6记录会员，获取更多回头客</span>
              </el-col>
              <el-col v-else class="Consumer-infor">
                <el-row class="Consumer-box">
                  <span>上一单消费： {{ PreOrderNum }}</span>
                  <span class="pay-status">支付成功</span>
                </el-row>
                <el-row class="Consumer-amount">
                  <el-col :span="11">
                    <span>
                      应收&nbsp;
                      <strong>{{ preActualPayAmount }}</strong>
                    </span>
                    <span>
                      实收&nbsp;
                      <strong>{{ preCashAmount }}</strong>
                    </span>
                  </el-col>
                  <el-col :span="2">
                    <el-divider direction="vertical"></el-divider>
                  </el-col>
                  <el-col :span="11">
                    <span>找零(￥)</span>
                    <span
                      class="needChange"
                    >{{ (parseFloat(preCashAmount) - parseFloat(preActualPayAmount)).toFixed(2) }}</span>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-header>
          <el-main>
            <el-row class="manage">
              <el-tabs tabPosition="right" style="height: 100%;">
                <el-tab-pane label="推荐">
                  <div class="recommend-cont">
                    <span>会员常购</span>
                    <span>尚未录入会员</span>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="默认分组">
                  <el-row class="group-cont">
                    <div class="group-list flex flex-hw">
                      <div class="group-item">
                        <span>手机壳</span>
                        <span>￥&nbsp;54.00</span>
                      </div>
                      <div class="group-item">
                        <span>手机壳</span>
                        <span>￥&nbsp;54.00</span>
                      </div>
                      <div class="group-item">
                        <span>手机壳</span>
                        <span>￥&nbsp;54.00</span>
                      </div>
                      <div class="group-item">
                        <span>手机壳</span>
                        <span>￥&nbsp;54.00</span>
                      </div>
                    </div>
                  </el-row>
                </el-tab-pane>
              </el-tabs>
            </el-row>
          </el-main>
        </el-container>
      </el-col>
      <!-- 点击‘结算’按钮显示区域 -->
      <el-drawer
        title="结算区域"
        :visible.sync="payDrawer"
        :with-header="false"
        size="100%"
        :close="closeAccount"
        class="payBlock"
      >
        <el-row class="payCont flex flex-hb">
          <el-col>
            <div class="backTip flex flex-hc flex-vc" @click="closeAccount()">
              点击该区域&nbsp;返回&nbsp;
              <strong>Esc</strong>
            </div>
          </el-col>
          <el-col class="flex" style="background:#fff;">
            <el-container>
              <el-aside>
                <el-row class="payContL">
                  <el-row>
                    <el-button class="cleanData" id="cleanData" @click="cleanData()">
                      作废&nbsp;
                      <strong>F1</strong>
                    </el-button>
                  </el-row>
                  <el-row class="discount-method">
                    <span>优惠方式</span>
                    <el-row>
                      <el-button class="discount-item" id="wholeDis" @click="mainFuns(8)">
                        <i class="pay-method-icon el-icon-wallet"></i>
                        整单折扣&nbsp;
                        <strong>F10</strong>
                      </el-button>
                      <el-button class="discount-item" id="WholePrice" @click="mainFuns(9)">
                        <i class="pay-method-icon el-icon-wallet"></i>
                        整单改价&nbsp;
                        <strong>F4</strong>
                      </el-button>
                    </el-row>
                  </el-row>
                  <el-row class="pay-method">
                    <span>支付方式</span>
                    <el-row class>
                      <el-button class="discount-item">
                        <i class="pay-method-icon el-icon-wallet"></i>
                        现金&nbsp;
                      </el-button>
                      <!-- <el-button class="discount-item">
                          <i class="pay-method-icon el-icon-wallet"></i>
                          支付扫码&nbsp;
                        </el-button>
                        <el-button class="discount-item">
                          <i class="pay-method-icon el-icon-wallet"></i>
                          储值支付&nbsp;
                        </el-button>
                        <el-button class="discount-item">
                          <i class="pay-method-icon el-icon-wallet"></i>
                          积分支付&nbsp;
                        </el-button>
                        <el-button class="discount-item">
                          <i class="pay-method-icon el-icon-wallet"></i>
                          赊账&nbsp;
                      </el-button>-->
                    </el-row>
                  </el-row>
                </el-row>
              </el-aside>
              <el-main class="payContR">
                <!-- 结算部分 -->
                <el-row class="payPage">
                  <el-col class="payData">
                    <el-row class="preAmount flex">
                      <el-col>商品合计</el-col>
                      <el-col>{{ objData.data.preAmount }}</el-col>
                    </el-row>

                    <el-row class="preAmount flex remark">
                      <el-col>商品优惠</el-col>
                      <el-col>{{ objData.data.goodsDis }}</el-col>
                    </el-row>
                    <el-row class="preAmount flex remark">
                      <el-col>整单优惠</el-col>
                      <el-col>{{ objData.data.wholeDis }}</el-col>
                    </el-row>
                    <el-row class="preAmount flex bold">
                      <el-col>应收</el-col>
                      <el-col>{{ (parseFloat(objData.data.preAmount)+parseFloat(objData.data.goodsDis)+parseFloat(objData.data.wholeDis)).toFixed(2) }}</el-col>
                    </el-row>
                    <el-row class="inputNum flex flex-vc">
                      <el-input type="text" v-model="objData.data.num" maxlength="10">
                        <template slot="prepend">现金</template>
                      </el-input>
                    </el-row>
                    <el-row class="preAmount flex bold">
                      <el-col>{{ parseFloat(objData.data.num?objData.data.num:'0')-(parseFloat(objData.data.preAmount)+parseFloat(objData.data.goodsDis)+parseFloat(objData.data.wholeDis)) >=0 ? '找零':'仍需'}}</el-col>
                      <el-col>{{ (parseFloat(objData.data.num?objData.data.num:'0')-(parseFloat(objData.data.preAmount)+parseFloat(objData.data.goodsDis)+parseFloat(objData.data.wholeDis))).toFixed(2) }}</el-col>
                    </el-row>
                  </el-col>
                  <div class="Calcu-num" @click.capture="Calcul($event)">
                    <table cellspacing="6">
                      <tr>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                        <td class="addNum">￥100</td>
                      </tr>
                      <tr>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td class="addNum">￥50</td>
                      </tr>
                      <tr>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td class="addNum">￥20</td>
                      </tr>
                      <tr>
                        <td>0</td>
                        <td class="dotTd">.</td>
                        <td class="backTd"></td>
                        <td class="addNum">￥10</td>
                      </tr>
                      <tr>
                        <td class="sureBtn" colspan="4">完成结账</td>
                      </tr>
                    </table>
                  </div>
                </el-row>
              </el-main>
            </el-container>
          </el-col>
        </el-row>
      </el-drawer>

      <ModifyData
        class="modifyData"
        v-if="modifyData.flag>1"
        :modifyData="modifyData"
        @modifyCb="modifyCb"
      ></ModifyData>

      <Print :printFlag="printFlag" @changeFlag="changeFlag" @getPrinters="getPrinters"></Print>

    </el-row>
    
  </section>
</template>

<script>
import { ipcRenderer } from "electron";
import ModifyData from "../../components/ModifyData";
import Print from "../../components/Print";
export default {
  components: {
    ModifyData,
    Print
  },
  data() {
    return {
      OrderNum: "", //销售单
      PreOrderNum: "", //上一笔消费单
      searchData: [], //搜索内容数据
      inputShopName: "", //搜索框input数据
      shopsData: [], //商品表格数据
      groupsData: [], //默认分组数据
      currentRow: null, //选中行的商品数据
      payDrawer: false, //打开结算区域
      fixedDialog: false,
      saleActualSum: "0.00", //商品实际金额
      surePayFlag: false, //是否确认付款
      objData: { data: {} }, //结算数据包
      clickNum: 0, //点击计算器数字的次数
      preActualPayAmount: 0, //上一笔应付总金额
      preCashAmount: 0, //上一笔实付金额
      modifyData: {
        flag: 0, //打开对话框的标识 0：关闭；1：结算；2：会员；3：数量；
        // width: "", //对话框的宽度
        tabFlag: 0, //优惠标志 0：不是，1：是
        //hadTitle: 1, //对话框的头部0:没有，1：有
        title: "",
        data: {} //需要处理的数据
      }, //组件修改的相关数据
      nowtime: "", //当前时间
      onLine: navigator.onLine, //网络在线、离线
      printFlag: {}, //打印内容
      printList: [] //打印机列表
    };
  },
  created() {
    this.creatOrder();
    //  键盘按键事件
    var that = this;
    document.onkeydown = function(e) {
      var key = window.event.key;
      if (that.payDrawer) {
        switch (key) {
          case "F4":
            that.mainFuns(9);
            break;
          case "F10":
            that.mainFuns(8);
            break;
          default:
            break;
        }
      } else {
        switch (key) {
          case "+":
            that.mainFuns(1);
            break;
          case "F6":
            that.mainFuns(2);
            break;
          case "*":
            that.mainFuns(3);
            break;
          case "Delete":
            that.mainFuns(4);
            break;
          case "F4":
            that.mainFuns(5);
            break;
          case "F8":
            that.mainFuns(6);
            break;
          case "F11":
            that.mainFuns(7);
            break;
          case "F1":
            that.mainFuns(10);
            break;
          default:
            break;
        }
      }
    };
    
  },
  mounted() {
    // 获取数据
    this.searchData = this.loadShops();
    this.groupsData = this.loadGrounps();

    // 获取商品表格的缓存数据
    if (this.$S.get("shopsData") && this.$S.get("shopsData").length > 0) {
      this.shopsData = this.$S.get("shopsData");
      this.upData();
      this.getCurrentRow();
      // this.getPayItem();
    }
    this.getPayItem();
    this.printFlag = { getPrinters: true };

    // 监听网络在线、离线
    window.addEventListener("online", this.updateOnline);
    window.addEventListener("offline", this.updateOnline);
  },
  beforeDestroy() {
    window.removeEventListener("online", this.updateOnline);
    window.removeEventListener("offline", this.updateOnline);
  },
  watch: {
    objData: {
      deep: true,
      handler: function(newVal, oldVal) {
        if (newVal.data.num) {
          var newNum = this.$F.trim(newVal.data.num);
          // 输入框最大长度为10
          if (newNum.length > 10) {
            this.objData.data.num = newNum.slice(0, 10);
            return;
          }
          this.objData.data.num = this.$F.PosDecimal2(newNum).toString();
        }
      }
    }
  },
  methods: {
    getPrinters(printList) {
      this.printList = printList;
    },
    //获取选中行
    getCurrentRow() {
      if (this.$S.get("currentRow")) {
        var currentRow = this.$S.get("currentRow");
        var curIndex = -1;
        this.shopsData.find((item, index) => {
          if (item.id === currentRow.id) {
            curIndex = index;
          }
        });
        this.setCurrent(this.shopsData[curIndex]);
      }
    },
    // 获取上一笔交易记录的缓存数据
    getPayItem() {
      var allOrder = this.$S.get("allOrder");
      if (allOrder && allOrder[0]) {
        this.PreOrderNum = allOrder[0].orderNum;
        this.surePayFlag = true;
        this.preActualPayAmount = allOrder[0].acturalPay;
        this.preCashAmount = allOrder[0].cash;
      }
    },
    // 更新网络连接状态
    updateOnline(e) {
      const { type } = e;
      this.onLine = type === "online";
      if (this.onLine) {
        // 如果在线
        this.$message({
          showClose: true,
          type: "success",
          message: "网络连接成功!"
        });

        //连接api，更新商品数据，清空缓存的商品数据：shopsData

        // 连接api，将缓存的订单流水数据更新到后台数据中，清空缓存的订单流水：allOrder
      } else {
        // 如果离线，
        this.$message({
          showClose: true,
          type: "success",
          message: "网络连接失败!"
        });
        // 缓存商品数据：shopsData；
        this.$S.set("shopsData", this.shopsData);
        // 当结算时，缓存订单流水数据：allOrder
      }
    },
    // 创建订单号
    creatOrder() {
      if (!this.$S.get("OrderNum")) {
        this.OrderNum = this.getTime(1);
        this.$S.set("OrderNum", this.OrderNum);
      } else this.OrderNum = this.$S.get("OrderNum");
    },
    // 创建订单号、获取当前时间
    getTime(flag) {
      // flag 1：获取当前时间创建订单号  2：获取当前时间创建订单结算时间
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      if (flag == 1) {
        return yy + "" + mm + "" + dd + "" + hh + "" + mf + "" + ss;
      } else if (flag == 2) {
        return yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      }
    },

    // 搜索框查询数据
    query(queryString, cb) {
      var searchData = this.searchData;
      var results = queryString
        ? searchData.filter(this.createFilter(queryString))
        : searchData;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },

    // 输入内容，筛选数据
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.shopName
            .toLowerCase()
            .indexOf(queryString.trim().toLowerCase()) === 0
        );
      };
    },

    // 加载商品列表数据
    loadShops() {
      return [
        {
          shopName: "1Apple 256GB 暗夜绿色 移动联通电信4G手机 双卡双待",
          shopCode: "0000100001",
          id: "0000100001",
          salePrice: "8000.00 ",
          num: 1,
          acturalPrice: "8000.00 "
        },
        {
          shopName: "2Apple 128GB 黑色 移动联通电信4G手机 双卡双待",
          id: "00002",
          salePrice: "6000.00 ",
          num: 1,
          acturalPrice: "6000.00 "
        },
        {
          shopName: "3Apple 256GB 金色 移动联通电信4G手机 双卡双待",
          id: "000.0003",
          shopCode: "000.0003",
          salePrice: "10000.00 ",
          num: 1,
          acturalPrice: "10000.00 "
        },
        {
          shopName: "4Apple 256GB 金色 移动联通电信4G手机 双卡双待",
          id: "00004",
          shopCode: "00004",
          salePrice: "10000.00 ",
          num: 1,
          acturalPrice: "10000.00 "
        },
        {
          shopName: "5戴尔14英寸轻薄笔记本电脑",
          id: "00005",
          shopCode: "00005",
          salePrice: "6000.00 ",
          num: 1,
          acturalPrice: "6000.00"
        },
        {
          shopName: "华为",
          id: "00006",
          shopCode: "00006",
          salePrice: "50.00 ",
          num: 1,
          acturalPrice: "50.00"
        },
        {
          shopName:
            "华为 HUAWEI nova 6 SE 麒麟810芯片4800万AI四摄40W超级快充8GB+128GB 樱雪晴空 全网通双卡双待",
          shopCode: "00007",
          id: "00007",
          salePrice: "2000",
          num: 1,
          acturalPrice: "2000 "
        }
      ];
    },
    // 加载商品列表数据
    loadGrounps() {
      return [
        {
          name: {
            name: "1Apple ",
            price: "12.00"
          }
        }
      ];
    },
    // 点击内容赋值到input
    selected(selectItem) {
      this.inputShopName = "";

      var curIndex = 0;
      var cbItem = this.shopsData.find((item, index) => {
        if (item.id == selectItem.id) {
          curIndex = index;
          return item;
        }
      });
      if (cbItem) {
        if (cbItem.BeforePrice) {
          cbItem.BeforePrice = "";
        }
        cbItem.num += 1;
        cbItem.acturalPrice = (
          parseFloat(cbItem.salePrice) * parseInt(cbItem.num)
        ).toFixed(2);
        this.setCurrent(this.shopsData[curIndex]);
        this.upData();
      } else {
        this.shopsData.unshift(selectItem);
        this.setCurrent(this.shopsData[curIndex]);
        this.upData();
      }
    },
    // 更新数据
    upData() {
      this.saleActualSum = (() => {
        var sum = 0;
        for (var i = 0; i < this.shopsData.length; i++) {
          sum += parseFloat(this.shopsData[i].acturalPrice);
        }
        return sum.toFixed(2);
      })();

      this.$S.set("shopsData", this.shopsData);
    },

    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
    },

    // 选中某行返回的数据,本地缓存
    selectedRow(val) {
      this.currentRow = val;
      this.$S.set("currentRow", val);
    },
    //多种按钮功能函数
    mainFuns(type) {
      // type: 1:结算，2：会员；3：数量；5：售价；6：商品优惠；7：更多;8：整单折扣；9：整单改价 10：作废
      if (!this.shopsData.length) {
        this.warn("请添加商品！");
        return;
      } else if (!this.currentRow) {
        this.warn("请选择商品！");
        return;
      }
      switch (type) {
        case 1:
          this.payPage();
          return;
          break;
        case 3:
          this.modifyNum();
          return;
          break;
        case 4:
          this.delShops();
          return;
          break;
        case 5:
          this.modifyPrice();
          return;
          break;
        case 6:
          this.modifyDis();
          return;
          break;
        case 8:
          this.modifyWholeDis();
          return;
          break;
        case 9:
          this.modifyWholePri();
          return;
        case 10:
          this.cleanData();
          return;
          break;
        default:
          this.warn("该功能暂未开放！");
          return;
          break;
      }
    },
    // 打开结算页
    payPage() {
      this.payDrawer = true;
      // 商品优惠总金额
      var goodsDis = (() => {
        var sum = 0;
        for (var i = 0; i < this.shopsData.length; i++) {
          if (this.shopsData[i].BeforePrice) {
            sum += parseFloat(
              parseFloat(this.shopsData[i].acturalPrice) -
                parseFloat(this.shopsData[i].BeforePrice)
            );
          }
        }
        return sum.toFixed(2);
      })();
      // 商品合计
      var goodsSum = (() => {
        var sum = 0;
        for (var i = 0; i < this.shopsData.length; i++) {
          sum += parseFloat(
            parseFloat(this.shopsData[i].salePrice) * this.shopsData[i].num
          );
        }
        return sum.toFixed(2);
      })();

      var acturalPay = (parseFloat(goodsSum) + parseFloat(goodsDis)).toFixed(2);
      this.objData = {
        flag: 1,
        data: {
          num: acturalPay,
          preAmount: goodsSum,
          goodsDis: goodsDis,
          wholeDis: this.objData.data.wholeDis
            ? this.objData.data.wholeDis
            : "0.00"
        }
      };
    },
    //点击计算器
    Calcul(event) {
      var e = event.target;
      if (e.nodeName == "TD") {
        if (this.$F.isNumber(e.innerText)) {
          this.CalNum(e);
        } else {
          this.CalNotNum(e);
        }
      }
    },
    // 点击数字区域
    CalNum(e) {
      // 初次点击数字，初始内容
      if (!this.clickNum) {
        this.objData.data.num = e.innerText;
        this.clickNum = 1;
        return;
      } else this.objData.data.num += e.innerText;
    },
    // 点击不是数字区域
    CalNotNum(e) {
      var num = this.$F.trim(this.objData.data.num);
      switch (e.className) {
        //点击'.'
        case "dotTd":
          if (num.indexOf(".") >= 0) {
            this.warn("请输入正确数值！");
            return;
          }
          this.objData.data.num += e.innerText;
          break;
        //点击 '< '
        case "backTd":
          this.objData.data.num = num.slice(0, num.length - 1);
          break;
        // 点击￥100区域
        case "addNum":
          this.objData.data.num = (
            parseFloat(num) + parseFloat(e.innerText.replace("￥", ""))
          ).toString();
          break;
        // 点击确定按钮
        case "sureBtn":
          if (!num || parseFloat(num) < 0) {
            this.warn("请输入大于0的数值！");
            return;
          }
          if (
            parseFloat(num ? num : "0") -
              (parseFloat(this.objData.data.preAmount) +
                parseFloat(this.objData.data.goodsDis) +
                parseFloat(this.objData.data.wholeDis)) <
            0
          ) {
            this.warn("请支付剩余金额！");
            return;
          }
          this.modifyCb(this.objData);
          break;
        default:
          return;
      }
    },
    // 修改数量
    modifyNum() {
      this.modifyData = {
        flag: 3,
        tabFlag: 0,
        title: "改数量：" + this.currentRow.shopName,
        data: {
          num: this.currentRow.num.toString(),
          preAmount: this.currentRow.salePrice.toString()
        }
      };
    },
    // 删除商品
    delShops() {
      this.$confirm("是否删除选中的商品?", "提示", {
        type: "warning"
      })
        .then(() => {
          var index = this.shopsData.indexOf(this.currentRow);
          if (index > -1) {
            this.shopsData.splice(index, 1);
          }
          this.upData();
          this.$message({
            showClose: true,
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            showClose: true,
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 修改售价
    modifyPrice() {
      this.modifyData = {
        flag: 5,
        tabFlag: 0,
        title: "改售价：" + this.currentRow.shopName,
        data: {
          num: this.currentRow.salePrice.toString()
        }
      };
    },

    // tabFlag修改 优惠与折扣
    modifyDis() {
      this.modifyData = {
        flag: 6,
        tabFlag: 1,
        title: "商品",
        data: {
          num: this.currentRow.acturalPrice.toString(),
          preAmount: this.currentRow.BeforePrice
            ? this.currentRow.BeforePrice
            : this.currentRow.acturalPrice.toString()
        }
      };
    },

    // 修改整单折扣
    modifyWholeDis() {
      var preAmount =
        parseFloat(this.objData.data.preAmount) +
        parseFloat(this.objData.data.goodsDis);
      var acturalPay =
        parseFloat(this.objData.data.preAmount) +
        parseFloat(this.objData.data.goodsDis) +
        parseFloat(this.objData.data.wholeDis);
      var num = (acturalPay / preAmount) * 10;
      this.modifyData = {
        flag: 8,
        tabFlag: 0,
        title: "整单折扣",
        data: {
          preAmount: preAmount.toFixed(2),
          acturalPay: acturalPay.toFixed(2),
          num: num.toFixed(1)
        }
      };
    },

    // 打开整单改价
    modifyWholePri() {
      var preAmount =
        parseFloat(this.objData.data.preAmount) +
        parseFloat(this.objData.data.goodsDis);
      var acturalPay =
        parseFloat(this.objData.data.preAmount) +
        parseFloat(this.objData.data.goodsDis) +
        parseFloat(this.objData.data.wholeDis);
      this.modifyData = {
        flag: 9,
        tabFlag: 0,
        //hadTitle: 1,
        title: "整单优惠",
        data: {
          preAmount: preAmount.toFixed(2),
          num: this.objData.data.num.toString()
        }
      };
    },

    // 修改内容的返回函数
    modifyCb(obj) {
      // obj.flag: 1:结算，2：会员；3：数量；5：售价；6：商品优惠；7：更多;8：整单折扣；9：整单改价 10：作废
      switch (obj.flag) {
        case 1:
          this.payCb(obj);
          break;
        case 3:
          this.currentRow.num = parseInt(obj.data.num);
          this.currentRow.acturalPrice = (
            parseFloat(this.currentRow.salePrice) * parseInt(obj.data.num)
          ).toFixed(2);
          this.upData();
          break;
        case 5:
          this.currentRow.salePrice = parseFloat(obj.data.num).toFixed(2);
          this.currentRow.acturalPrice = (
            parseFloat(this.currentRow.salePrice) *
            parseInt(this.currentRow.num)
          ).toFixed(2);
          this.currentRow.BeforePrice = "";
          this.upData();
          break;
        case 6:
          this.currentRow.BeforePrice = (
            parseFloat(this.currentRow.salePrice) *
            parseInt(this.currentRow.num)
          ).toFixed(2);
          this.currentRow.acturalPrice = parseFloat(obj.data.num).toFixed(2);
          this.upData();

          break;
        case 8:
          this.objData.data.num = obj.data.acturalPay;
          this.objData.data.wholeDis = (
            parseFloat(obj.data.acturalPay) - parseFloat(obj.data.preAmount)
          ).toFixed(2);
          break;
        case 9:
          this.objData.data.num = obj.data.num;
          this.objData.data.wholeDis = (
            parseFloat(obj.data.num) - parseFloat(obj.data.preAmount)
          ).toFixed(2);

          break;
        default:
          break;
      }
    },
    // 结算-确认付款后的回调
    payCb(obj) {
      this.setAllOrder();
      this.creatOrder();
      this.initData();
      // 检测本机设置的打印小票方式，如果是'销售后自动打印小票'，则启动打印，
      this.saledPrint();

    },
    // 存储上一笔销售进流水单中
    setAllOrder() {
      if (!this.$S.get("allOrder")) {
        var allOrder = [];
      } else {
        var allOrder = this.$S.get("allOrder");
      }
      this.preActualPayAmount = (
        parseFloat(this.objData.data.preAmount) +
        parseFloat(this.objData.data.goodsDis) +
        parseFloat(this.objData.data.wholeDis)
      ).toFixed(2);
      this.preCashAmount = parseFloat(this.objData.data.num).toFixed(2);
      this.PreOrderNum = this.OrderNum;
      var orderItem = {
        orderNum: this.OrderNum, //订单号
        goodsSum: this.objData.data.preAmount, //商品合计
        goodsDis: this.objData.data.goodsDis, //商品优惠
        wholeDis: this.objData.data.wholeDis, //整单优惠
        acturalPay: this.preActualPayAmount, //实际应付
        cash: this.preCashAmount, //现金
        needChange: (
          parseFloat(this.preCashAmount) - parseFloat(this.preActualPayAmount)
        ).toFixed(2), ///找零
        shopsData: this.shopsData, //商品信息
        shopNum: this.shopsData.length, //商品件数
        time: this.getTime(2) //结算时间
      };
      this.$voice('收款'+this.preCashAmount +'元');

      allOrder.unshift(orderItem);
      this.$S.set("allOrder", allOrder);
      this.$S.set("OrderNum", "");
    },
    // 销售单打印
    saledPrint() {
      var mainForm = this.$S.get("settings-form");
      if (
        mainForm &&
        mainForm.printTicket.value.find(item => "saled" === item)
      ) {
        var encryption = false;
        if (mainForm.printTicket.value.find(item => "encryption" === item)) {
          encryption = true;
        }
        if (this.checkPrint(this.$store.state.deviceName)) {
          this.printFlag = {
            flag: 2,
            data: true,
            deviceName: this.$store.state.deviceName,
            padding: mainForm.printData.paddingVal || "",
            encryption: encryption
          };
        }
      }
    },
    // 判断打印机状态, 本地获取打印机
    checkPrint(deviceName) {
      if (this.printList.length <= 0) {
        this.$message({
          message: "没有检测到打印设备！",
          type: "error"
        });
        return false;
      }
      var deviceName = deviceName || "";
      var printer = this.printList.find(item => item.name === deviceName);

      if (printer && printer.status === 0) {
        return true;
      } else if (!deviceName) {
        this.$message({
          message: "请先设置其他打印机",
          type: "error"
        });
        return false;
      } else {
        this.$message({
          message: "当前打印机不可用,请重新设置",
          type: "error"
        });
        return false;
      }
    },
    // 改变打印标识
    changeFlag() {
      this.printFlag.data = false;
    },
    // 作废
    cleanData() {
      this.$confirm(
        "该操作将会清空当前销售数据，请确认本单是否需要作废？",
        "提示"
      )
        .then(_ => {
          this.initData();
        })
        .catch(_ => {});
    },

    // 结算完成后，初始化相关数据
    initData() {
      // flg 1:点击结算后，数据初始化，空：是作废数据

      this.payDrawer = false; //结算区域
      this.objData = { data: {} };
      this.clickNum = 0;
      this.searchData = this.loadShops();
      this.shopsData = []; //商品表格数据
      this.currentRow = null; //选中行的商品数据
      this.saleActualSum = (0).toFixed(2);

      this.$S.set("shopsData", this.shopsData);
    },

    // 关闭结算页抽屉
    closeAccount() {
      this.payDrawer = false;
      this.clickNum = 0;
    },

    // 提示信息
    warn(string) {
      this.$message({
        message: string,
        type: "warning",
        showClose: true
      });
    },

    //测试请求接口数据
    getViewInfo() {
      this.$http
        .request({
          url:
            "https://wepaas-test.ebsig.com/model/object/panel/get/user?appid=5d3acc4da175340d700049b5",
          method: "get",
          data: {}
        })
        .then(res => {
          console.log(res, "===res===");
        });
    }
  }
};
</script>

 
<style scoped>
@import "../../assets/css/openOrder.css";
</style>
<style  lang="scss" >
.search .el-icon-search {
  color: #3c85f1;
  font-weight: bold;
  font-size: 16px;
}
.search .el-autocomplete {
  width: 100%;
}

.goods-listBox .el-table {
  position: inherit;
}

.manage .el-tabs__item.is-active {
  color: #ff3d3a;
}
.Collection .el-main {
  padding: 0;
}
.manage .el-tabs__active-bar {
  background-color: #ff3d3a !important;
  right: 0;
  width: 4px !important;
  left: auto !important;
}
.manage .el-tabs__item:hover {
  color: rgb(172, 97, 95);
}
.manage .el-tabs__nav-wrap::after {
  background: none;
}

.modifyData {
  .el-dialog {
    width: 520px;
  }
  .el-dialog__header {
    text-align: left;
  }
  .el-dialog__footer {
    padding: 0;
  }
  .el-dialog__body {
    border-top: 1px solid #e5e5e5;
    padding: 20px;
  }
}
.payPage {
  height: 100%;
  .payData {
    padding: 30px 20px 10px 20px;
  }
  .Calcu-num {
    width: 100%;
    height: 100%;
    table {
      background: #eceef4;
      border-collapse: initial;
      // position: absolute;
      // bottom: 0;
    }

    table td {
      border-radius: 4px;
      background: #fff;
      padding: 0px 30px;
      color: #454646;
      line-height: 49px;
      border: none;
    }
    .sureBtn {
      background: #ff3d3a;
      color: #fff;
      font-size: 17px;
      font-weight: bold;
      letter-spacing: 2px;
    }
  }

  .preAmount {
    padding-bottom: 20px;
    margin: 0px;
    font-size: 16px;
  }
  .inputNum {
    padding: 20px 0 30px 0;
    margin: 0;
    border-top: 1px solid #e5e5e5;
    .el-input {
      font-size: 16px;
    }
  }
}

.el-tabs__nav-wrap::after {
  background: none;
}

.tabFlag {
  .el-dialog__body {
    border: 0;
    padding: 0;
  }
  .el-dialog__header {
    padding: 0;
  }
  .el-tabs__header {
    padding: 10px 10px 10px 20px;
    margin: 0 40px 0 0;
  }
  .el-tabs__content {
    padding: 20px;
    border-top: 1px solid #e5e5e5;
  }
  .inputNum {
    padding: 0;
    margin: 0 0 20px 0;
  }
}
.preAmount {
  margin-bottom: 20px;
  .el-col:first-child {
    text-align: left;
  }
  .el-col:last-child {
    text-align: right;
  }
}
.inputNum {
  width: 100%;
  input {
    text-align: right;
  }
}
.bottomCont {
  position: absolute;
  width: 100%;
  bottom: 0;
}
.bold {
  font-weight: bolder;
  font-size: 18px;
  // border-bottom: 1px solid #e5e5e5;
}
.remark {
  color: rgb(248, 102, 35);
  margin-bottom: 20px;
}

.btn-box .el-button + .el-button {
  margin-left: auto;
}
</style>
 
